//
//  logOnViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-6-17.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "logOnViewController.h"
#import "regViewController.h"
#import "ZPUserModel.h"
#import "MBProgressHUD.h"

@interface logOnViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
@property (nonatomic,strong) NSArray *logResult;
@end

@implementation logOnViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _disornoBt.selected = YES;
    self.title = @"登录";
    
    self.tableView.backgroundColor = ColorFromRGB(0xF6F6F6);
    self.navigationItem.backBarButtonItem =[[UIBarButtonItem alloc]
                                            initWithTitle:@" "
                                            style:UIBarButtonItemStyleBordered
                                            target:nil
                                            action:nil];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]
                                            initWithTitle:@"取消"
                                            style:UIBarButtonItemStyleBordered
                                            target:self
                                            action:@selector(dismiss)];
    
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                             initWithTitle:@"注册"
                                             style:UIBarButtonItemStyleBordered
                                             target:self
                                             action:@selector(toReg)];
    
    [_disornoBt setImage:[UIImage imageNamed:@"switch_close"] forState:UIControlStateSelected];
    [_disornoBt setImage:[UIImage imageNamed:@"switch"] forState:UIControlStateNormal];
    
    [_bt_LogIn.layer setCornerRadius:4.0];
    [_bt_LogIn setBackgroundColor:ColorFromRGB(0xFF0100)];
}
-(void)toReg
{
    regViewController *regVC = [self.storyboard instantiateViewControllerWithIdentifier:@"regViewController"];
    [self.navigationController pushViewController:regVC animated:NO];
}
-(UIBarPosition)positionForBar:(id<UIBarPositioning>)bar {
    return UIBarPositionTopAttached;
}


- (IBAction)disorno:(id)sender {
    _disornoBt.selected =! _disornoBt.selected;
    [self.pwd setSecureTextEntry:_disornoBt.selected];
    
}

- (void)dismiss{
    
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self];
    }];
}

- (IBAction)didLogIn:(id)sender {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"登录中";
    NSString *isuname;
    if ([self validateEmail:_userName.text]) {
        isuname = @"2";
    }else if([self validateMobile:_userName.text]){
        isuname = @"3";
    }else{
        isuname = @"1";
    }
    
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
    NSString *deviceToken = dataDic[@"devicetoken"];
    NSDictionary *params;
    if ([deviceToken isEqual:[NSNull null]] || deviceToken.length < 1) {
        params = @{@"username": _userName.text,
                   @"password": _pwd.text,
                   @"isuname": isuname,
                   @"channel":@"3",
                   @"apptype": @"1"};
    } else {
        params = @{@"username": _userName.text,
                   @"password": _pwd.text,
                   @"isuname": isuname,
                   @"channel":@"3",
                   @"model":deviceToken,
                   @"apptype": @"1"};
    }
    
    
    [manager POST:APIURL@"ucmembers/onLogin.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *jsonString = operation.responseString;
        self.logResult= (NSArray *)responseObject;
        if ([_logResult valueForKey:@"result"]) {
            NSError* err = nil;
            ZPUserModel* userInfo = [[ZPUserModel alloc] initWithString:jsonString error:&err];
            
            
            //[dataDic setValue:_userName.text forKey:@"userName"];
            [dataDic setValue:userInfo.userName forKey:@"userName"];
            [dataDic setValue:userInfo.nickName forKey:@"nickName"];
            [dataDic setValue:_pwd.text forKey:@"passwd"];
            [dataDic setValue:userInfo.token forKey:@"token"];
            [dataDic setValue:userInfo.mobile forKey:@"mobile"];
            [dataDic setValue:userInfo.memberId forKey:@"memberId"];
            
            [dataDic writeToFile:path atomically:YES];
            hud.labelText = @"登陆成功";
            [hud hide:YES];
            [CheckLoginObject saveLoginWithStatus:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"combineCart" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
            [self dismiss];
        }else{
            [hud hide:YES];
            [CheckLoginObject saveLoginWithStatus:NO];
            NSString *errorNotice = [NSString stringWithFormat:@"%@",[_logResult valueForKey:@"error"]];
            UIAlertView *logError = [[UIAlertView alloc]initWithTitle:@"登陆失败" message:errorNotice delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [logError show];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [hud hide:YES];
        [CheckLoginObject saveLoginWithStatus:NO];
        //DO:(@"Error: %@", error);
        
    }];
}


- (BOOL)validateEmail:(NSString *)userName{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:userName];
}

- (BOOL)validateMobile:(NSString *)userName
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:userName];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 15;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


#pragma mark -UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.5;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 14.5, self.tableView.frame.size.width, 0.5)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    return lineV;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0.5)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    return lineV;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
